<template>
  <div class="exam-take-container">
    <!-- 考试头部信息 -->
    <div class="exam-header">
      <div class="exam-info">
        <h2>{{ examInfo?.name }}</h2>
        <div class="exam-meta">
          <span>科目: {{ examInfo?.subjectName }}</span>
          <span>总分: {{ examInfo?.totalScore }} 分</span>
          <!-- <span>及格分: {{ examInfo?.passScore || '暂无' }}</span> -->
        </div>
      </div>

      <!-- 考试计时和控制 -->
      <div class="exam-controls">
        <div class="timer">
          <el-icon>
            <Timer />
          </el-icon>
          <span>剩余时间: {{ formatTime(examStore.remainingTime) }}</span>
        </div>
        <div class="progress-info">
          <span>已答: {{ examStore.answeredCount }} / {{ totalQuestions }}</span>
          <span>未答: {{ examStore.unansweredQuestionIds?.length || 0 }}</span>
        </div>
        <el-button type="primary" @click="submitExam">交卷</el-button>
      </div>
    </div>

    <!-- 考试内容区 -->
    <div class="exam-content">
      <!-- 左侧导航栏 -->
      <div class="question-nav">
        <div v-for="(bigQuestion, bigIndex) in examInfo?.bigQuestions" :key="'bq-' + bigIndex" class="big-question-nav">
          <div class="big-question-title">{{ bigQuestion.name }}</div>
          <div class="question-nav-items">
            <div v-for="(question, qIndex) in bigQuestion.questions" :key="'q-' + question.paperDetailId"
              class="question-nav-item" :class="getQuestionNavClass(question.paperDetailId)"
              @click="navigateToQuestion(question.paperDetailId)">
              {{ (bigIndex + 1) }}-{{ (qIndex + 1) }}
            </div>
          </div>
        </div>

        <div class="nav-status-info">
          <div class="status-item"><span class="status-dot answered"></span> 已答</div>
          <div class="status-item"><span class="status-dot unanswered"></span> 未答</div>
          <div class="status-item"><span class="status-dot marked"></span> 标记</div>
        </div>
      </div>

      <!-- 右侧答题区 -->
      <div class="question-area">
        <template v-for="(bigQuestion, bigIndex) in examInfo?.bigQuestions" :key="'bq-'+bigIndex">
          <div class="big-question-header">
            <h3>{{ bigIndex + 1 }}. {{ bigQuestion.name }}</h3>
          </div>

          <div v-for="(question, qIndex) in bigQuestion.questions" :key="'q-' + question.paperDetailId"
            :id="'question-' + question.paperDetailId" class="question-item">
            <div class="question-header">
              <div class="question-title">
                {{ (bigIndex + 1) }}-{{ (qIndex + 1) }} {{ question.questionName }}
                <span class="question-score">({{ question.score }}分)</span>
              </div>
              <div class="question-actions">
                <el-button size="small" :type="isQuestionMarked(question.paperDetailId) ? 'warning' : 'info'"
                  @click="toggleMarkQuestion(question.paperDetailId)">
                  {{ isQuestionMarked(question.paperDetailId) ? '取消标记' : '标记' }}
                </el-button>
              </div>
            </div>

            <!-- 题目内容展示 -->
            <div class="question-content" v-if="question.questionContent">{{ question.questionContent }}
            </div>

            <!-- 答题区 -->
            <div class="answer-area">
              <!-- 单选题 -->
              <template v-if="question.questionTypeId === 1">
                <el-radio-group v-model="answerData[question.paperDetailId]"
                  @change="saveQuestionAnswer(question.paperDetailId, bigIndex)">
                  <el-radio v-for="option in question.options" :key="option.key" :label="option.key">
                    {{ option.key }}: {{ option.value }}
                  </el-radio>
                </el-radio-group>
              </template>

              <!-- 多选题 -->
              <template v-else-if="question.questionTypeId === 2">
                <el-checkbox-group v-model="answerData[question.paperDetailId]"
                  @change="saveQuestionAnswer(question.paperDetailId, bigIndex)">
                  <el-checkbox v-for="option in question.options" :key="option.key" :label="option.key">
                    {{ option.key }}: {{ option.value }}
                  </el-checkbox>
                </el-checkbox-group>
              </template>

              <!-- 填空题 -->
              <template v-else-if="question.questionTypeId === 3">
                <el-input v-model="answerData[question.paperDetailId]" type="textarea" :rows="3" placeholder="请填写答案"
                  @change="saveQuestionAnswer(question.paperDetailId, bigIndex)" />
              </template>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="exam-footer">
      <el-button-group>
        <el-button @click="prevQuestion" :disabled="!hasPrev">上一题</el-button>
        <el-button @click="nextQuestion" :disabled="!hasNext">下一题</el-button>
      </el-button-group>

      <el-button type="danger" @click="showUnanswered">
        未答题 <el-badge :value="examStore.unansweredQuestionIds.length"
          :hidden="examStore.unansweredQuestionIds.length === 0" />
      </el-button>

      <el-button type="primary" @click="submitExam">交卷</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useExamStore } from '@/stores/modules/exam-student'
import { useUserStore } from '@/stores/modules/user-student'
import { getExamDetail, getExamProgress, submitExam as submitExamApi } from '@/api/student/exam'
import { useExamTimer } from '@/composables/useExamTimer'
import { useExamMonitor } from '@/composables/useExamMonitor'
import { Timer } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const examStore = useExamStore()
const userStore = useUserStore()

// 考试ID
const examId = route.params.id
// 考试信息
// const examInfo = ref({
//   name: '',
//   studentPaperId: 1,
//   subjectName: '',
//   totalScore: 0,
//   passScore: 0,
//   bigQuestions: []
// })
const examInfo = ref(null)
// 总题目数量
const totalQuestions = computed(() => {
  if (!examInfo.value?.bigQuestions) return 0
  return examInfo.value?.bigQuestions.reduce(
    (total, bq) => total + bq.questions.length, 0
  )
})
// 答案数据
const answerData = ref({})

// paperDetailId 到 question 的映射
const paperDetailIdToQuestionMap = ref(new Map())

// 初始化考试数据
const initExam = async () => {
  try {
    // 获取考试详情
    const { data } = await getExamDetail(examId)

    if (examStore.currentExam == null || examStore.currentExam.studentPaperId !== data?.studentPaperId) {
      // 设置当前考试
      console.log("xxxxxxxxxxxxxx")

      examStore.setCurrentExam(data)
    }
    // examStore.setCurrentExam(data)
    // Object.assign(examInfo.value, examStore.currentExam.value)

    examInfo.value = examStore.currentExam
    // console.log(examInfo.value)
    // console.log(examStore.currentExam.value)

    // 初始化映射
    initQuestionMaps()

    // 初始化答案数据
    initAnswerData()

    // 滚动到当前题目
    if (examStore.currentQuestionId) {
      scrollToQuestion(examStore.currentQuestionId)
    }
  } catch (error) {
    console.error('获取考试信息失败:', error)
    ElMessage.error('获取考试信息失败，请刷新页面重试')
  }
}

// 初始化题目映射
const initQuestionMaps = () => {
  paperDetailIdToQuestionMap.value.clear()

  if (examInfo.value?.bigQuestions) {
    examInfo.value?.bigQuestions.forEach(bq => {
      bq.questions.forEach(q => {
        paperDetailIdToQuestionMap.value.set(q.paperDetailId, q)
      })
    })
  }
}

// 根据paperDetailId获取题目
const getQuestionByPaperDetailId = (paperDetailId) => {
  return paperDetailIdToQuestionMap.value.get(paperDetailId)
}

// 初始化答案数据
const initAnswerData = () => {
  // console.log("触发钩子")

  // 初始化答案对象
  if (examInfo.value?.bigQuestions) {
    examInfo.value?.bigQuestions.forEach(bq => {
      bq.questions.forEach(q => {
        // 如果题目已有学生答案（从后端获取）
        if (q.studentAnswer != null && q.studentAnswer.trim() !== '') {
          answerData.value[q.paperDetailId] = parseAnswer(q.studentAnswer, q.questionTypeId)

          if (examStore.questionNavStatus[q.paperDetailId] === null) {
            examStore.questionNavStatus[q.paperDetailId] = 1 // 标记为已答
          }

        } else {
          // answerData.value[q.paperDetailId] = getDefaultAnswerValue(q.questionTypeId)
          if (examStore.questionNavStatus[q.paperDetailId] === null) {
            examStore.questionNavStatus[q.paperDetailId] = 0 // 标记为未答
          }
        }
      })
    })
  }

  // console.log(answerData)
  // 对象， {1:"A"
  //        2:""
  //      }

  // 初始化考试答题情况(pinia中的answers,有对象类型转换（早期遗留）)
  examStore.initSavedAnswers(Object.entries(answerData.value).map(([paperDetailId, answer]) => ({
    paperDetailId: parseInt(paperDetailId),
    answer: typeof answer === 'object' ? JSON.stringify(answer) : answer,
    timeSpent: 0
  })))
}



// 获取默认答案值
const getDefaultAnswerValue = (questionTypeId) => {
  switch (questionTypeId) {
    case 1: // 单选
      return ''
    case 2: // 多选
      return []
    case 3: // 填空
    default:
      return ''
  }
}

// 解析已保存的答案
const parseAnswer = (answerStr, questionTypeId) => {
  try {
    switch (questionTypeId) {
      case 1: // 单选
        return answerStr
      case 2: // 多选
        return answerStr.split(',')
      case 3: // 填空
      default:
        return answerStr
    }
  } catch (e) {
    console.error('解析答案失败:', e)
    return getDefaultAnswerValue(questionTypeId)
  }
}

// 保存答案
const saveQuestionAnswer = async (paperDetailId, bigIndex) => {
  const question = getQuestionByPaperDetailId(paperDetailId)
  if (!question) return

  let answerStr = answerData.value[paperDetailId]

  // 转换多选答案为字符串
  if (question.questionTypeId === 2 && Array.isArray(answerStr)) {
    answerStr = answerStr.join(',')
  }

  // 更新pinia（可考虑用ref转换examInfo自动同步）
  examStore.currentExam.bigQuestions.forEach(
    big => {
      console.log(big)
      big.questions.forEach(
        q => {
          if (q.paperDetailId === paperDetailId) {
            q.answer = answerStr
          }
        }
      )
    }
  )

  await examStore.saveAnswer(paperDetailId, answerStr, question.id)
}

// 获取所有题目数组（按paperDetailId）
const getAllQuestionsArray = () => {
  if (!examInfo.value?.bigQuestions) return []
  return examInfo.value?.bigQuestions.flatMap(bq => bq.questions)
}

// 上一题
const prevQuestion = () => {
  if (!hasPrev.value) return

  const allQuestionsArr = getAllQuestionsArray()
  const currentIndex = allQuestionsArr.findIndex(q => q.paperDetailId === examStore.currentQuestionId)

  if (currentIndex > 0) {
    const prevQuestion = allQuestionsArr[currentIndex - 1]
    navigateToQuestion(prevQuestion.paperDetailId)
  }
}

// 下一题
const nextQuestion = () => {
  if (!hasNext.value) return

  const allQuestionsArr = getAllQuestionsArray()
  const currentIndex = allQuestionsArr.findIndex(q => q.paperDetailId === examStore.currentQuestionId)

  if (currentIndex < allQuestionsArr.length - 1) {
    const nextQuestion = allQuestionsArr[currentIndex + 1]
    navigateToQuestion(nextQuestion.paperDetailId)
  }
}

// 跳转到指定题目
const navigateToQuestion = (paperDetailId) => {
  examStore.setCurrentQuestion(paperDetailId)
  scrollToQuestion(paperDetailId)
}

// 滚动到指定题目
const scrollToQuestion = (paperDetailId) => {
  setTimeout(() => {
    const element = document.getElementById(`question-${paperDetailId}`)
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  }, 100)
}

// 显示未答题
const showUnanswered = () => {
  const unansweredIds = examStore.unansweredQuestionIds

  if (unansweredIds.length === 0) {
    ElMessage.success('您已经答完所有题目')
    return
  }

  navigateToQuestion(unansweredIds[0])
  ElMessage.warning(`还有 ${unansweredIds.length} 题未作答`)
}

// 标记题目
const toggleMarkQuestion = (paperDetailId) => {
  const isMarked = isQuestionMarked(paperDetailId)
  examStore.markQuestion(paperDetailId, !isMarked)
}

// 判断题目是否被标记
const isQuestionMarked = (paperDetailId) => {
  return examStore.questionNavStatus[paperDetailId] === 2
}

// 获取题目导航样式
const getQuestionNavClass = (paperDetailId) => {
  const status = examStore.questionNavStatus[paperDetailId] || 0

  switch (status) {
    case 1: return 'answered'
    case 2: return 'marked'
    default: return 'unanswered'
  }
}

// 是否有上一题
const hasPrev = computed(() => {
  if (!examStore.currentQuestionId) return false
  const allQuestionsArr = getAllQuestionsArray()
  const currentIndex = allQuestionsArr.findIndex(q => q.paperDetailId === examStore.currentQuestionId)
  return currentIndex > 0
})

// 是否有下一题
const hasNext = computed(() => {
  if (!examStore.currentQuestionId) return false
  const allQuestionsArr = getAllQuestionsArray()
  const currentIndex = allQuestionsArr.findIndex(q => q.paperDetailId === examStore.currentQuestionId)
  return currentIndex < allQuestionsArr.length - 1
})

// 提交试卷
const submitExam = async () => {
  // 检查是否存在未答题目
  const unansweredIds = examStore.unansweredQuestionIds

  if (unansweredIds.length > 0) {
    try {
      await ElMessageBox.confirm(
        `您还有 ${unansweredIds.length} 题未作答，确定要交卷吗？`,
        '提示',
        {
          confirmButtonText: '确定交卷',
          cancelButtonText: '继续作答',
          type: 'warning'
        }
      )
    } catch (e) {
      navigateToQuestion(unansweredIds[0])
      return
    }
  } else {
    try {
      await ElMessageBox.confirm(
        '确定要交卷吗？提交后将无法修改答案。',
        '提示',
        {
          confirmButtonText: '确定交卷',
          cancelButtonText: '继续作答',
          type: 'warning'
        }
      )
    } catch (e) {
      return
    }
  }

  try {
    // 同步所有答案
    await examStore.syncAnswers()

    // 提交试卷
    await submitExamApi(examId, {
      studentPaperId: examInfo.value?.studentPaperId,
      autoSubmit: false
    })

    ElMessage.success('提交成功')

    // 重置考试状态
    examStore.reset()

    // 跳转到成绩页面
    router.push(`/score/${examInfo.value.studentPaperId}`)
  } catch (error) {
    console.error('提交试卷失败:', error)
    ElMessage.error('提交试卷失败，请重试')
  }
}

// 使用考试计时器
const { formatTime } = useExamTimer()

// 使用考试监控
// const monitorSettings = computed(() => ({
//   allowSwitchScreen: examInfo.value.allowSwitchScreen || false,
//   maxSwitchCount: examInfo.value.maxSwitchCount || 3,
//   requireFullscreen: examInfo.value.requireFullscreen || true,
//   allowCopyPaste: examInfo.value.allowCopyPaste || false,
//   maxWarnings: examInfo.value.maxWarnings || 3
// }))

// const { initMonitor } = useExamMonitor(monitorSettings.value)

// 离开页面前确认
const beforeUnload = (e) => {
  e.preventDefault()
  e.returnValue = '考试尚未完成，确定要离开吗？'
}

onMounted(async () => {
  // 初始化考试数据
  await initExam()

  // 添加页面离开确认
  window.addEventListener('beforeunload', beforeUnload)

  // 初始化监控
  //   initMonitor()
})

onBeforeUnmount(() => {
  //   window.removeEventListener('beforeunload', beforeUnload)
})
</script>

<style scoped>
.exam-take-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.exam-info h2 {
  margin: 0 0 6px;
  font-size: 20px;
}

.exam-meta {
  display: flex;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.exam-controls {
  display: flex;
  align-items: center;
  gap: 24px;
}

.timer {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.progress-info {
  display: flex;
  gap: 12px;
  font-size: 14px;
}

.exam-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.question-nav {
  width: 200px;
  padding: 16px;
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.big-question-nav {
  margin-bottom: 16px;
}

.big-question-title {
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
}

.question-nav-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-nav-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.question-nav-item.unanswered {
  background-color: #f4f4f5;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.question-nav-item.answered {
  background-color: #d9ecff;
  border: 1px solid #a0cfff;
  color: #409eff;
}

.question-nav-item.marked {
  background-color: #fdf2e9;
  border: 1px solid #f8d2a0;
  color: #e6a23c;
}

.question-nav-item:hover {
  transform: scale(1.05);
}

.nav-status-info {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-dot.answered {
  background-color: #409eff;
}

.status-dot.unanswered {
  background-color: #909399;
}

.status-dot.marked {
  background-color: #e6a23c;
}

.question-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.big-question-header {
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.big-question-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.question-item {
  margin-bottom: 32px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.question-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.question-score {
  margin-left: 8px;
  color: #f56c6c;
  font-size: 14px;
}

.question-content {
  margin-bottom: 16px;
  color: #606266;
  line-height: 1.5;
}

.answer-area {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.exam-footer {
  display: flex;
  justify-content: space-between;
  padding: 12px 24px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>